//
//  CardDetailViewController.m
//  myhuibao
//
//  Created by 孙昕 on 14-2-19.
//  Copyright (c) 2014年 myhuibao. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "CardDetailViewController.h"
#import "SBJson.h"
#import "Config.h"
#import "RestaurantDetailViewController.h"
#import "LoginViewController.h"
#import "OMGToast.h"
@interface CardDetailViewController ()

@end

@implementation CardDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _MemberView.hidden=YES;
    _NotMemberView.hidden=NO;
    _vLevel.layer.masksToBounds=YES;
//    [_vLevel.layer setBorderColor:[[UIColor grayColor] CGColor]];
 //   [_vLevel.layer setBorderWidth:0.5f];
 //   [_vLevel.layer setCornerRadius:0];
    _vPoint.layer.masksToBounds=YES;
//    NSLog(@"%d",[[_vLevel.layer sublayers] count]);
 //   [_vPoint.layer setBorderColor:[[UIColor grayColor] CGColor]];
 //   [_vPoint.layer setBorderWidth:0.5f];
//    [_vPoint.layer setCornerRadius:0];
    _vConsume.layer.masksToBounds=YES;
 //   [_vConsume.layer setBorderColor:[[UIColor grayColor] CGColor]];
 //   [_vConsume.layer setBorderWidth:0.5f];
 //   [_vConsume.layer setCornerRadius:0];
    _lbDisInfo.layer.masksToBounds=YES;
    [_lbDisInfo.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_lbDisInfo.layer setBorderWidth:0.5f];
    [_lbDisInfo.layer setCornerRadius:5];
    _lbMemo.layer.masksToBounds=YES;
    [_lbMemo.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_lbMemo.layer setBorderWidth:0.5f];
    [_lbMemo.layer setCornerRadius:5];
    _lbShowMerchant.layer.masksToBounds=YES;
    [_lbShowMerchant.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_lbShowMerchant.layer setBorderWidth:0.5f];
    [_lbShowMerchant.layer setCornerRadius:10];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    dem=dispatch_semaphore_create(0);
    [self getResult];
    
}

-(void)dealloc
{
    dispatch_release(dem);
}

-(void)viewDidAppear:(BOOL)animated
{
    dispatch_semaphore_signal(dem);
    //if(event!=nil)
    //{
     //   [event signal];
   // }
    
}
-(void) getResult
{
    NSURL *url = [NSURL URLWithString:url_cardDetail];
    req=[ASIFormDataRequest requestWithURL:url];
    [req setPostValue:[NSString stringWithFormat:@"%d",_settingID] forKey:@"settingID"];
    int memberId = [[Config Instance] getMemberId];
    if(memberId != 0)
    {
        [req setPostValue:[NSString stringWithFormat:@"%d",memberId] forKey:@"memberID"];
    }
    [req setDidFinishSelector:@selector(finishResult:)];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDelegate: self];
    [req startAsynchronous];

}


-(void) finishResult:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    data = [dic valueForKey:@"data"];
    _lbDisInfo.frame=CGRectMake(20, 327, 280, 37);
    _vInfo.frame=CGRectMake(20, 366, 280, 110);
    _vLevel.hidden=NO;
    _vPoint.hidden=NO;
    _vConsume.hidden=NO;
    bool bPublish=[[data valueForKey:@"publish"] intValue];
    if(!bPublish)
    {
//        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"该会员卡已关闭"
//                                                      message:@""
//                                                     delegate:nil
//                                            cancelButtonTitle:@"确定"
//                                            otherButtonTitles:nil];
//        alert.tag=2;
//        [alert show];
//        [OMGToast showWithText:@"该会员卡已关闭" bottomOffset:100];
       if(_ParView!=nil)
       {
           _ParView.tag=1;
       }
        //event=[[NSCondition alloc] init];
        //[event signal];
        [NSThread detachNewThreadSelector:@selector(SycBack) toTarget:self withObject:nil];
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 36, self.view.frame.size.width, self.view.frame.size.height-36)];
        [view setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:view];
        //[self.navigationController popViewControllerAnimated:NO];
        return;
    }
    NSString *strImg=[NSString stringWithFormat:@"%@%@",url_image,[data valueForKey:@"tempPath"]];
    NSURL *imageUrl = [NSURL URLWithString:[strImg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
    UIImage *image = [UIImage imageWithData:imageData];
    [_ImageView setImage:image];
    _lbName.text=[data objectForKey:@"merchantName" ]==[NSNull null]?@"":[data objectForKey:@"merchantName" ];
    if([[Config Instance] getMemberId]==0 || [[data objectForKey:@"cardNO" ] intValue]==0)
    {
        _MemberView.hidden=YES;
        _NotMemberView.hidden=NO;
        //_lbNotMemberDisInfo.text=[data objectForKey:@"discountInfo" ];
        _btnDel.hidden=YES;
        _lbAlert.hidden=YES;
    }
    else
    {
        _MemberView.hidden=NO;
        _NotMemberView.hidden=YES;
        //_lbMemberDisInfo.text=[data objectForKey:@"discountInfo" ];
        _lbCardNo.text=[NSString stringWithFormat:@"卡号：%@",[data objectForKey:@"cardNO" ]];
        _lbMemberName.text=[[Config Instance] getName];
        _lbAlert.hidden=NO;
        _btnDel.hidden=NO;
    }
    int UpHeight=0;
    BOOL bDraw=NO;
    if([data objectForKey:@"levelName" ]!=[NSNull null])
    {
        _lbLevel.text=[data objectForKey:@"levelName" ];
        bDraw=YES;
    }
    else
    {
        UpHeight+=_vLevel.frame.size.height;
        _vLevel.hidden=YES;
    }
    if([data objectForKey:@"pointBalance" ]!=[NSNull null])
    {
        _lbPoint.text=[NSString stringWithFormat:@"%d",[[data objectForKey:@"pointBalance" ] intValue]];
        bDraw=YES;
    }
    else
    {
        UpHeight+=_vPoint.frame.size.height;
        _vPoint.hidden=YES;
    }
    if([data objectForKey:@"amountComulation" ]!=[NSNull null])
    {
        _lbConsume.text=[NSString stringWithFormat:@"%d",[[data objectForKey:@"amountComulation" ] intValue]];
        if(_vPoint.hidden==YES)
        {
            _vConsume.frame=CGRectMake(_vPoint.frame.origin.x, _vPoint.frame.origin.y, 280, _vConsume.frame.size.height);
        }
        bDraw=YES;
    }
    else
    {
        UpHeight+=_vConsume.frame.size.height;
        _vConsume.hidden=YES;
    }
    _lbGap1.hidden=YES;
    _lbGap2.hidden=YES;
    if(bDraw)
    {
        int h=_vLevel.frame.size.height+_vPoint.frame.size.height+_vConsume.frame.size.height-UpHeight;
        _vDT.hidden=NO;
        _vDT.frame=CGRectMake(_vLevel.frame.origin.x, _vLevel.frame.origin.y, 280, h);
        _vDT.layer.masksToBounds=YES;
        [_vDT.layer setBorderColor:[[UIColor grayColor] CGColor]];
        [_vDT.layer setBorderWidth:0.5f];
        [_vDT.layer setCornerRadius:0];
        if(_vPoint.hidden==NO)
        {
            _lbGap1.hidden=NO;
        }
        if(_vConsume.hidden==NO)
        {
            _lbGap2.hidden=NO;
        }
    }
    else
    {
        _vDT.hidden=YES;
    }
    _lbDisInfo.text=[data objectForKey:@"discountInfo" ];
    _lbDisInfo.numberOfLines=0;
    [_lbDisInfo sizeToFit];
    _lbDisInfo.frame=CGRectMake(20, _lbDisInfo.frame.origin.y-UpHeight, 280, _lbDisInfo.frame.size.height);
    _lbMemo.text=[data objectForKey:@"memo" ]==[NSNull null]?@"":[data objectForKey:@"memo" ];
    _vInfo.frame=CGRectMake(20, _lbDisInfo.frame.origin.y+_lbDisInfo.frame.size.height+2, 280, _vInfo.frame.size.height);
    
}


-(void) SycBack
{
   // [event wait];
    dispatch_semaphore_wait(dem, DISPATCH_TIME_FOREVER);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)OnBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)OnDel:(id)sender {
    UIAlertView * alert =[[UIAlertView alloc] initWithTitle:@"请确认是否删除此会员卡" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.tag=3;
    //alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    //((UITextField *)[alert textFieldAtIndex:0]) .delegate=self;
    //((UITextField *)[alert textFieldAtIndex:0]).tag=0;
    [alert show];

}

-(void) finishDel:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //    NSLog(@"%@",dic);
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        [self getResult];
    }
}

- (IBAction)GetMember:(id)sender {
    if([[Config Instance] getMemberId]==0)
    {
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        //    view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        return;
    }
    NSString *name=[[Config Instance] getName] ;
    if(name==nil || [name isEqualToString:@""])
    {
//        NameView=[[UIView alloc] init];
//        NameView.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
//        NameView.backgroundColor=[UIColor grayColor];
//        NameView.alpha=0.8;
//        UILabel *lb=[[UILabel alloc] init];
//        lb.frame=CGRectMake(90, 100, 140, 20);
//        lb.textAlignment=UITextAlignmentCenter;
//        lb.backgroundColor=[UIColor clearColor];
//        lb.text=@"请输入你的姓名";
//        [NameView addSubview:lb];
//        UITextField *textfield=[[UITextField alloc] init];
//        textfield.delegate=self;
//        textfield.frame=CGRectMake(60, 130, 200, 20);
//        textfield.backgroundColor=[UIColor whiteColor];
//        textfield.borderStyle=UITextBorderStyleRoundedRect;
//        [NameView addSubview:textfield];
//        UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
//        button.titleLabel.textAlignment=UITextAlignmentCenter;
//        [button setTitle:@"领取" forState:UIControlStateNormal] ;
//        button.frame=CGRectMake(100, 160, 40, 20);
//        [button addTarget:self action:@selector(SetName) forControlEvents:UIControlEventTouchUpInside];
//        [NameView addSubview:button];
//        UIButton *button1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
//        button1.titleLabel.textAlignment=UITextAlignmentCenter;
//        [button1 setTitle:@"取消" forState:UIControlStateNormal] ;
//        button1.frame=CGRectMake(180, 160, 40, 20);
//        [NameView addSubview:button1];
//        [button1 addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:NameView];
        UIAlertView * alert =[[UIAlertView alloc] initWithTitle:@"请输入姓名" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alert.tag=0;
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        ((UITextField *)[alert textFieldAtIndex:0]) .delegate=self;
        ((UITextField *)[alert textFieldAtIndex:0]).tag=0;
        [alert show];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification"
                                                  object:((UITextField *)[alert textFieldAtIndex:0])];

        return;
    }
    NSURL *url = [NSURL URLWithString:url_cardGet];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%d",_settingID] forKey:@"settingID"];
    [request setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getMemberId]] forKey:@"memberID"];
    [request setPostValue:[NSString stringWithFormat:@"%@",[[Config Instance] getPassword]] forKey:@"password"];
    [request setPostValue:[NSString stringWithFormat:@"%@",[[Config Instance] getName]] forKey:@"memberName"];
    [request setDidFinishSelector:@selector(finishGetMember:)];
    [request setShouldAttemptPersistentConnection:NO];
    [request setDelegate: self];
    [request startAsynchronous];
}

-(void)alertView : (UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==0)
    {
        if(buttonIndex==0)
        {
            return;
        }
        //得到输入框
        UITextField *lbName=[alertView textFieldAtIndex:0];
        NSString *lbtext=lbName.text;
        NSString *strErr=nil;
        if(lbtext==nil)
        {
            strErr=@"姓名不能为空! ";
        }
        NSString *name=[lbtext stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if([name isEqualToString:@""])
        {
            strErr=@"姓名不能为空! ";
        }
        else if([name length]>8)
        {
            strErr=@"姓名长度过长! ";
        }
        if(strErr!=nil)
        {
            UIAlertView * alert =[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@是否重新输入？",strErr] message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.tag=1;
            [alert show];
            return;
        }
        NSURL *url = [NSURL URLWithString:url_cardGet];
        ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
        [request setPostValue:[NSString stringWithFormat:@"%d",_settingID] forKey:@"settingID"];
        [request setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getMemberId]] forKey:@"memberID"];
        [request setPostValue:[NSString stringWithFormat:@"%@",[[Config Instance] getPassword]] forKey:@"password"];
        //UITextField *lbName=(UITextField*)[NameView.subviews objectAtIndex:1];
        [[Config Instance] setName:name];
        [request setPostValue:name forKey:@"memberName"];
        [request setDidFinishSelector:@selector(finishGetMember:)];
        [request setShouldAttemptPersistentConnection:NO];
        [request setDelegate: self];
        [request startAsynchronous];
    }
    else if(alertView.tag==1)
    {
        if(buttonIndex==1)
        {
            UIAlertView * alert =[[UIAlertView alloc] initWithTitle:@"请输入姓名" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.tag=0;
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            [alert show];
            ((UITextField *)[alert textFieldAtIndex:0]) .delegate=self;
             ((UITextField *)[alert textFieldAtIndex:0]).tag=0;
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                        name:@"UITextFieldTextDidChangeNotification"
                                                      object:((UITextField *)[alert textFieldAtIndex:0])];
        }
    }
    else if(alertView.tag==2)
    {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    else if(alertView.tag==3)
    {
        if(buttonIndex==1)
        {
            NSURL *url = [NSURL URLWithString:url_cardDel];
            ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
            [request setPostValue:[NSString stringWithFormat:@"%@",[data objectForKey:@"memberCardID" ]] forKey:@"memberCardID"];
            [request setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getMemberId]] forKey:@"memberID"];
            [request setPostValue:[NSString stringWithFormat:@"%@",[[Config Instance] getPassword]] forKey:@"password"];
            [request setDidFinishSelector:@selector(finishDel:)];
            [request setShouldAttemptPersistentConnection:NO];
            [request setDelegate: self];
            [request startAsynchronous];
        }
    }
}

-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==0)
    {
        [[NSNotificationCenter defaultCenter]removeObserver:self
                                                       name:@"UITextFieldTextDidChangeNotification"
                                                     object:((UITextField *)[alertView textFieldAtIndex:0])];
    }
}

-(void) finishGetMember:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    if([dic valueForKey:@"log"]!=[NSNull null] && [[dic valueForKey:@"log"] compare:@"登录已经过期，请重新登录" options:1]==NSOrderedSame)
    {
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
            view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        return;
    }
    _btnDel.hidden=NO;
    [self getResult];
}

- (IBAction)showMerchant:(id)sender {
    RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
    //传递商户id参数
    view.merchantId =[[data objectForKey:@"merchantID"] intValue];
    view.merchantType=[[data objectForKey:@"merchantType"] intValue];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [theTextField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    //if(textField.tag ==0)
    //{
     //   NSInteger strLength = textField.text.length - range.length + string.length;
     //   return (strLength <= 8);
   // }
    return YES;
}

-(CGFloat)calculateTextHeight:(CGFloat)widthInput Content:(NSString *)strContent{
    CGSize constraint = CGSizeMake(widthInput, 20000.0f);
    CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    //CGFloat height = MAX(size.height, 44.0f);
    return size.height;
}

-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 8) {
                textField.text = [toBeString substringToIndex:8];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > 8 ) {
            textField.text = [toBeString substringToIndex:8];
        }
    }
}

@end
